import { contextBridge, ipcRenderer } from 'electron';
import type { HttpRequestConfig, HttpResponse } from '../common/types/http-ipc';

/**
 * 前端可访问的 ElectronAPI 接口
 * 只保留核心的HTTP API和认证功能
 */
interface ElectronAPI {
  // 统一的 HTTP API
  httpRequest: (config: HttpRequestConfig) => Promise<HttpResponse>;

  // 类型安全的 API 调用
  api: {
    // 认证相关
    login: (phone: string, password: string) => Promise<any>;
    register: (phone: string, password: string, name?: string) => Promise<any>;
    sendCode: (phone: string, type: number) => Promise<any>;
    loginWithCode: (phone: string, code: string) => Promise<any>;
    registerWithCode: (phone: string, code: string) => Promise<any>;

    // 主页管理
    getHomePages: () => Promise<any[]>;
    addHomePage: (homepage: any) => Promise<any>;
    updateHomePage: (id: string, updates: any) => Promise<any>;
    deleteHomePage: (id: string) => Promise<any>;

    // 视频相关
    getVideos: (profileId?: string) => Promise<any[]>;

    // 抖音相关
    getDouyinMainPageInfo: (url: string) => Promise<any>;

    // 认证令牌管理
    setAuthToken: (token: string | null) => Promise<{ success: boolean }>;
  };
}

// 通过 contextBridge 暴露安全的 API 给渲染进程
const electronAPI: ElectronAPI = {
  // 统一的 HTTP API
  httpRequest: (config) => ipcRenderer.invoke('http-request', config),

  // 类型安全的 API 调用
  api: {
    // 认证相关
    login: (phone, password) => ipcRenderer.invoke('api-login', phone, password),
    register: (phone, password, name) => ipcRenderer.invoke('api-register', phone, password, name),
    sendCode: (phone, type) => ipcRenderer.invoke('api-send-code', phone, type),
    loginWithCode: (phone, code) => ipcRenderer.invoke('api-login-with-code', phone, code),
    registerWithCode: (phone, code) => ipcRenderer.invoke('api-register-with-code', phone, code),

    // 主页管理
    getHomePages: () => ipcRenderer.invoke('api-get-homepages'),
    addHomePage: (homepage) => ipcRenderer.invoke('api-add-homepage', homepage),
    updateHomePage: (id, updates) => ipcRenderer.invoke('api-update-homepage', id, updates),
    deleteHomePage: (id) => ipcRenderer.invoke('api-delete-homepage', id),

    // 视频相关
    getVideos: (profileId) => ipcRenderer.invoke('api-get-videos', profileId),

    // 抖音相关
    getDouyinMainPageInfo: (url) => ipcRenderer.invoke('api-get-douyin-main-page-info', url),

    // 认证令牌管理
    setAuthToken: (token) => ipcRenderer.invoke('set-auth-token', token),
  },
};

contextBridge.exposeInMainWorld('electronAPI', electronAPI);

// 扩展 Window 接口，使 TypeScript 能够识别 window.electronAPI
declare global {
  interface Window {
    electronAPI: ElectronAPI;
  }
}